package me.mouse.Lottery;

import java.util.Collection;
import java.util.HashMap;
import java.util.Random;

import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.inventory.ItemStack;

public class LotteryMachine {

	private HashMap<Integer, ItemStack> Item = new HashMap<>();
	private HashMap<ItemStack, Integer> Chance = new HashMap<>();
	private String Name;
	private String Info;
	private double Price;

	public LotteryMachine(String Name) {
		this.Name = Name;
	}

	public void addItem(ItemStack item, int chance) {
		int number = Item.keySet().toArray().length + 1;
		Item.put(number, item);
		Chance.put(item, chance);
	}

	public int getItemChance(ItemStack item) {
		return Chance.get(item);
	}

	public int getItemChance(int number) {
		return Chance.get(Item.get(number));
	}

	public int getAllChance() {
		Collection<Integer> cs = Chance.values();
		Object[] objs = cs.toArray();
		int ac = 0;
		for (Object obj : objs) {
			ac = ac + (Integer) obj;
		}
		return ac;
	}

	public ItemStack[] getAllItem() {
		Collection<ItemStack> citems = Item.values();
		Object[] objs = citems.toArray();
		ItemStack[] items = new ItemStack[objs.length];
		for (int i = 0; i < objs.length; i++) {
			items[i] = (ItemStack) objs[i];
		}
		return items;
	}

	public int getItemNumber() {
		return Item.size();
	}

	public void setName(String Name) {
		this.Name = Name;
	}

	public String getName() {
		return Name;
	}

	public void setInfo(String Info) {
		this.Info = Info.replaceAll("&", "��");
	}

	public String getInfo() {
		return Info;
	}

	public void removeItem(int number) {
		Chance.remove(Item.get(number));
		Item.remove(number);
	}

	public void save() {
		FileConfiguration machine = Lottery.load("machine.yml");
		machine.set(Name + ".info", Info);
		machine.set(Name + ".price", Price);
		for (int i = 1; i <= getItemNumber(); i++) {
			machine.set(Name + ".item." + i + ".item", Item.get(i));
			machine.set(Name + ".item." + i + ".chance",
					Chance.get(Item.get(i)));
		}
		Lottery.save(machine, "machine.yml");
	}

	public void remove() {
		FileConfiguration machine = Lottery.load("machine.yml");
		machine.set(Name, null);
		Lottery.save(machine, "machine.yml");
	}

	public double getPrice() {
		return Price;
	}

	public void setPrice(double Price) {
		this.Price = Price;
	}

	public synchronized ItemStack getRandomItem() {
		Random r = new Random();
		int i = r.nextInt(getAllChance());
		int allchance = 0;
		for (ItemStack item : Item.values()) {
			if (i < allchance + Chance.get(item)) {
				return new ItemStack(item);
			}
			allchance = allchance + Chance.get(item);
		}
		return null;
	}
}
